package com.rbac.web.common;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import java.lang.reflect.Type;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * @author gengaoliu
 */
public class GsonLocalDate implements JsonSerializer<LocalDate>, JsonDeserializer<LocalDate> {

  public static final String PATTERN = "yyyy-MM-dd";
  public static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern(PATTERN);

  @Override
  public LocalDate deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
      throws JsonParseException {
    return LocalDate.parse(json.getAsString(), FORMATTER);
  }

  @Override
  public JsonElement serialize(LocalDate src, Type typeOfSrc, JsonSerializationContext context) {
    return new JsonPrimitive(src.format(FORMATTER));
  }
}
